﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using SymmetricEncription.Controls;
using Org.BouncyCastle.Crypto.Parameters;

namespace SymmetricEncription.Presenters
{
    public class ParametersInputStep: ProcessStepBase
    {
        private List<IBlockCipher> supportedCiphers = new List<IBlockCipher>()
                                                          {
                                                              new AesEngine(),
                                                              new DesEngine(),
                                                              new IdeaEngine(),
                                                          };

        public List<IBlockCipher> SupportedCiphers
        {
            get { return supportedCiphers; }
        }

        private IBlockCipher selectedCipher;
        public IBlockCipher SelectedCipher
        {
            get { return selectedCipher; }
            set
            {
                if (selectedCipher != value)
                {
                    selectedCipher = value;
                    RaisePropertyChanged("SelectedCipher");
                }
            }
        }

        public ParametersInputStep() : base(null, false)
        {
            this.Title = "Алгоритм AES.\nВвод параметров шифрования";
            this.SelectedCipher = this.supportedCiphers[0];
        }

        private DataInput stepUIControl = new DataInput();
        public override System.Windows.UIElement StepUIControl
        {
            get { return this.stepUIControl; }
        }

        public override ProcessStepBase GetNextStep()
        {
            try
            {
                var key = this.stepUIControl.biKey.GetByteArray();
                var data = this.stepUIControl.biData.GetByteArray();

                KeyParameter parameters;
                if(this.selectedCipher is DesEngine)
                {
                    parameters = new DesParameters(key);
                }
                else
                {
                    parameters = new KeyParameter(key);
                }

                BufferedBlockCipher cipher = new BufferedBlockCipher(this.selectedCipher);

                ProcessStepBase lastStep;
                cipher.Init(true, parameters, this, out lastStep);

                byte[] outBytes = new byte[data.Length];

                int len1 = cipher.ProcessBytes(data, 0, data.Length, outBytes, 0, lastStep, out lastStep);

                //cipher.DoFinal(outBytes, len1, lastStep, out lastStep);

                lastStep = new FinalStep(lastStep, outBytes);

                return this.nextStep;
            }
            catch (Exception ex)
            {
                return new ExceptionStep(ex, this);
            }
        }
    }
}
